<?php
/**
 * 路由器应用管理
 */
class Application {
    
    /**
     * 初始化路由方式
     * 
     * @return void
     */
    public static function init()
    {
        //huanran.zhao
        Router::decodeUrl();//为空时解释当前URL
        $controller = !empty($_POST['app'])?$_POST['app']:(!empty($_REQUEST['app'])?$_REQUEST['app']:'index');
        $action = !empty($_POST['act'])?$_POST['act']:(!empty($_REQUEST['act'])?$_REQUEST['act']:'index');
        $_GET['app'] = $controller;
        $_GET['act'] = $action;
        self::defineConst($controller, $action);

	    Behavior::checkRefresh();
    }
     
    
	/**
	 * 执行控制器的方法
	 * 
	 * @return void
	 */
	public function run() 
	{
		$controller = CONTROLLER_NAME . 'App';
		$action = ACTION_NAME . 'Act';
		
	    // 检测控制器、方法是否存在，否则跳转至404页面
		if(!class_exists($controller) || !method_exists($controller, $action))
		{
		   if(My::is_ajax())
				die(json_encode(array('statusCode'=>300,'message'=>'404 Not Found')));
			else
				include_once(PUB_DIR.'share/404.html');
			send_http_status(404);
			exit;
		}

		$cls_parent = class_parents($controller);
		if($cls_parent !== false)
		{
    		$parent_name = array_shift($cls_parent);
    		$parent_obj = new $parent_name ();
    		$method = '_initialize';
    		if (method_exists($parent_obj, $method)) $parent_obj-> $method (); // 执行父类的初始化方法
		}
      
		$controller_obj = MagicFactory :: getInstance($controller);
		$controller_obj->$action();
	}

    /**
     * 定义常量
     * 
     * @param string $controller
     * @param string $action
     * 
     * @return void
     */
    public static function defineConst($controller, $action) 
    {
        $scriptName = $_SERVER['SCRIPT_NAME'];
        $documentRoot = str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']);
        $scriptFileName = str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']);
        $project = $root = null;
        
        // 域名指向环境
        if(stripos($documentRoot, '/public') !== false)
        {
            $project = $pub = '/';
        }
        else  // 本地配置环境
        {
            $baseName = basename($scriptName);
            $scriptNameArr = array_filter(explode('/', str_replace($baseName, '', $scriptName)));
            $pos = stripos($scriptName, '/public/');
            if($pos !== false)
            {
                $project = substr($scriptName, 0, $pos+1);
            }
            else
            {
                $pos2 = stripos($scriptName, $baseName);
                $project = substr($scriptName, 0, $pos2);
            }
            $pub = $project.'Public/';
        }
        
        // 开启伪静态
        if(C('open_rewrite'))
        {
            $root = str_replace(array('/Public', '/index.php'), array('', ''), $scriptName).'/';
        }
        else
        {
            $root = $scriptName;
        }
        
        define('__PROJECT__', $project);
        define('__ROOT__', $root);
        define('__PUB__', $pub);
        define('__APP__', __PUB__.strtolower(APP_NAME).'/');
        define('__SHARE__',  __PUB__.'share/');
        define('__PLUG__', __PUB__.'share/plug/');
        
        // 当前控制器名称
        define('CONTROLLER_NAME', (empty ($controller) ? 'Index' : ucfirst($controller)));
        // 当前操作名称
        define('ACTION_NAME', (empty ($action) ? 'index' : $action));
        
        /*
        print_r($_SERVER);
        $a = get_defined_constants(true);
        print_r($a['user']);
        */
    }
	
}
